<template>
  <view class="income-edit-container">
    <view class="page-header">
      <text class="page-title">编辑收入记录</text>
      <text class="page-subtitle">修改员工收入信息</text>
    </view>

    <view v-if="pageLoading" class="page-loading-container">
      <view class="loading-spinner"></view>
      <text class="loading-text">加载数据中...</text>
    </view>

    <view v-else class="form-container">
      <view class="form-section">
        <text class="section-title">基本信息</text>
        
        <view class="form-item">
          <text class="form-label required">选择员工</text>
          <picker 
            mode="selector" 
            :range="userList" 
            range-key="displayName"
            :value="selectedUserIndex"
            @change="onUserChange"
          >
            <view class="picker-view">
              <text class="picker-text">{{ selectedUserName || '请选择员工' }}</text>
            </view>
          </picker>
          <text v-if="errors.user_id" class="error-text">{{ errors.user_id }}</text>
        </view>

        <view class="form-item">
          <text class="form-label required">所属月份</text>
          <picker mode="date" fields="month" :value="formData.year_month" @change="onMonthChange">
            <view class="picker-view">
              <text class="picker-text">{{ formData.year_month || '请选择月份' }}</text>
            </view>
          </picker>
          <text v-if="errors.year_month" class="error-text">{{ errors.year_month }}</text>
        </view>
      </view>

      <view class="form-section">
        <text class="section-title">收入明细</text>
        
        <view class="form-item">
          <text class="form-label required">基本工资（元）</text>
          <uni-easyinput 
            v-model="formData.base_salary"
            type="number"
            placeholder="请输入基本工资"
            :clearable="true"
            @input="calculateTotal"
          />
        </view>

        <view class="form-item">
          <text class="form-label">提成金额（元）</text>
          <uni-easyinput 
            v-model="formData.commission_amount"
            type="number"
            placeholder="请输入提成金额"
            :clearable="true"
            @input="calculateTotal"
          />
        </view>

        <view class="form-item">
          <text class="form-label">奖金（元）</text>
          <uni-easyinput 
            v-model="formData.bonus_amount"
            type="number"
            placeholder="请输入奖金"
            :clearable="true"
            @input="calculateTotal"
          />
        </view>

        <view class="form-item">
          <text class="form-label">扣款（元）</text>
          <uni-easyinput 
            v-model="formData.deduction_amount"
            type="number"
            placeholder="请输入扣款金额"
            :clearable="true"
            @input="calculateTotal"
          />
        </view>

        <view class="form-item">
          <text class="form-label">分红（元）</text>
          <uni-easyinput 
            v-model="formData.dividend_amount"
            type="number"
            placeholder="请输入分红金额"
            :clearable="true"
            @input="calculateTotal"
          />
        </view>

        <view class="form-item">
          <text class="form-label">总收入（元）</text>
          <view class="calculated-value">
            <text class="value-text">¥{{ totalIncome }}</text>
          </view>
        </view>
      </view>

      <view class="form-section">
        <text class="section-title">其他信息</text>
        
        <view class="form-item">
          <text class="form-label">备注</text>
          <textarea 
            v-model="formData.remarks" 
            class="form-textarea" 
            placeholder="请输入备注信息（选填）"
            maxlength="500"
          />
        </view>

        <view class="form-item">
          <text class="form-label required">状态</text>
          <view class="status-display">
            <view :class="['status-badge', getStatusClass(formData.status)]">
              {{ getStatusText(formData.status) }}
            </view>
            
            <!-- 已拒绝状态显示拒绝原因 -->
            <view v-if="formData.status === 4 && formData.rejection_reason" class="rejection-info">
              <text class="rejection-label">拒绝原因：</text>
              <text class="rejection-reason">{{ formData.rejection_reason }}</text>
            </view>
          </view>
        </view>
      </view>

      <view class="form-actions">
        <button class="btn btn-cancel" @click="handleCancel">取消</button>
        <!-- 已拒绝状态显示重新提交按钮 -->
        <button v-if="formData.status === 4" class="btn btn-warning" @click="handleResubmit">重新提交审批</button>
        <!-- 待审批状态可以保存 -->
        <button v-if="formData.status === 1" class="btn btn-primary" @click="handleSubmit">保存</button>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'

const pageLoading = ref(true)
const incomeId = ref('')

// 员工列表相关
const userList = ref([])
const selectedUserIndex = ref(-1)
const selectedUserName = ref('')

const formData = reactive({
  user_id: '',
  year_month: '',
  base_salary: '',
  commission_amount: '',
  bonus_amount: '',
  deduction_amount: '',
  dividend_amount: '',
  total_income: 0,
  remarks: '',
  status: 1,
  rejection_reason: ''
})

const errors = reactive({
  user_id: '',
  year_month: ''
})

const totalIncome = computed(() => {
  const base = parseFloat(formData.base_salary) || 0
  const commission = parseFloat(formData.commission_amount) || 0
  const bonus = parseFloat(formData.bonus_amount) || 0
  const deduction = parseFloat(formData.deduction_amount) || 0
  const dividend = parseFloat(formData.dividend_amount) || 0
  const total = base + commission + bonus - deduction + dividend
  formData.total_income = total
  return total.toFixed(2)
})

onMounted(async () => {
  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1]
  incomeId.value = currentPage.options.id || ''
  
  if (!incomeId.value) {
    uni.showToast({ title: '缺少收入记录ID', icon: 'none' })
    setTimeout(() => {
      uni.redirectTo({ url: '/pages/business/income_records/list' })
    }, 1500)
    return
  }
  
  await loadUserList()
  await loadIncomeData()
  pageLoading.value = false
})

// 加载员工列表
async function loadUserList() {
  try {
    // 调用云对象方法查询员工列表（所有员工，排除患者）
    const userQueryObj = uniCloud.importObject('dh-user-query')
    const result = await userQueryObj.listStaff('with_role')
    
    if (result.code === 200 && result.data) {
      // 格式化数据以匹配原有的数据结构
      userList.value = result.data.map(user => ({
        _id: user._id,
        displayName: user.displayName,
        realName: user.realName
      }))
      
      if (userList.value.length === 0) {
        console.warn('未找到员工')
      }
    } else {
      console.error('查询员工列表失败:', result.message)
      uni.showToast({ 
        title: result.message || '查询员工列表失败', 
        icon: 'none' 
      })
    }
  } catch (error) {
    console.error('加载员工列表失败:', error)
    uni.showToast({ title: '加载员工列表失败', icon: 'none' })
  }
}

// 员工选择改变
function onUserChange(e) {
  const index = e.detail.value
  selectedUserIndex.value = index
  if (index >= 0 && index < userList.value.length) {
    const selectedUser = userList.value[index]
    formData.user_id = selectedUser._id
    selectedUserName.value = selectedUser.displayName
    errors.user_id = ''
  }
}

async function loadIncomeData() {
  try {
    // 调用云对象方法获取收入记录信息
    const incomeRecordsObj = uniCloud.importObject('dh-income_records')
    const result = await incomeRecordsObj.getIncomeRecordById(incomeId.value)
    
    if (result.code === 200 && result.data) {
      const data = result.data
      Object.assign(formData, {
        user_id: data.user_id || '',
        year_month: data.year_month || '',
        base_salary: data.base_salary?.toString() || '',
        commission_amount: data.commission_amount?.toString() || '',
        bonus_amount: data.bonus_amount?.toString() || '',
        deduction_amount: data.deduction_amount?.toString() || '',
        dividend_amount: data.dividend_amount?.toString() || '',
        remarks: data.remarks || '',
        status: data.status || 1,
        rejection_reason: data.rejection_reason || ''
      })
      
      // 设置用户选择器的选中项
      if (data.user_id && userList.value.length > 0) {
        const userIndex = userList.value.findIndex(u => u._id === data.user_id)
        if (userIndex !== -1) {
          selectedUserIndex.value = userIndex
          selectedUserName.value = userList.value[userIndex].displayName
        }
      }
    } else {
      throw new Error(result.message || '收入记录不存在')
    }
  } catch (err) {
    console.error('加载收入记录失败:', err)
    uni.showToast({ title: err.message || '加载失败', icon: 'none' })
    setTimeout(() => {
      uni.redirectTo({ url: '/pages/business/income_records/list' })
    }, 1500)
  }
}

// 获取状态文本
function getStatusText(status) {
  const statusMap = {
    1: '待审批',
    2: '已审批',
    3: '已发放',
    4: '已拒绝'
  }
  return statusMap[status] || '未知'
}

// 获取状态样式类
function getStatusClass(status) {
  const classMap = {
    1: 'status-pending',
    2: 'status-approved',
    3: 'status-paid',
    4: 'status-rejected'
  }
  return classMap[status] || 'status-pending'
}

function onMonthChange(e) {
  const value = e.detail.value
  if (value) {
    const parts = value.split('-')
    formData.year_month = `${parts[0]}-${parts[1]}`
  }
  errors.year_month = ''
}

function onStatusChange(e) {
  formData.status = parseInt(e.detail.value)
}

function calculateTotal() {
  // 触发computed重新计算
}

function validateForm() {
  let isValid = true
  
  if (!formData.user_id || formData.user_id.trim().length === 0) {
    errors.user_id = '请输入员工ID'
    isValid = false
  } else {
    errors.user_id = ''
  }
  
  if (!formData.year_month) {
    errors.year_month = '请选择所属月份'
    isValid = false
  } else {
    errors.year_month = ''
  }
  
  return isValid
}

async function handleSubmit() {
  if (!validateForm()) {
    uni.showToast({ title: '请检查表单错误', icon: 'none' })
    return
  }
  
  try {
    uni.showLoading({ title: '保存中...' })
    
    const submitData = {
      ...formData,
      base_salary: parseFloat(formData.base_salary) || 0,
      commission_amount: parseFloat(formData.commission_amount) || 0,
      bonus_amount: parseFloat(formData.bonus_amount) || 0,
      deduction_amount: parseFloat(formData.deduction_amount) || 0,
      dividend_amount: parseFloat(formData.dividend_amount) || 0,
      update_time: Date.now()
    }
    
    // 调用云对象方法更新收入记录
    const incomeRecordsObj = uniCloud.importObject('dh-income_records')
    const result = await incomeRecordsObj.updateIncomeRecord(incomeId.value, submitData)
    
    uni.hideLoading()
    
    if (result.code === 200) {
      uni.showToast({ title: result.message || '更新成功', icon: 'success' })
      setTimeout(() => {
        uni.redirectTo({ url: '/pages/business/income_records/list' })
      }, 1500)
    } else {
      uni.showToast({ title: '更新失败', icon: 'none' })
    }
  } catch (err) {
    console.error('更新失败:', err)
    uni.hideLoading()
    uni.showToast({ title: err.message || '更新失败', icon: 'none' })
  }
}

// 重新提交审批
async function handleResubmit() {
  // 先验证表单
  if (!validateForm()) {
    uni.showToast({ title: '请检查表单错误', icon: 'none' })
    return
  }
  
  uni.showModal({
    title: '重新提交审批',
    content: '将保存当前修改并重新提交审批，状态将变更为"待审批"。确定继续吗？',
    confirmText: '确定',
    cancelText: '取消',
    success: async (res) => {
      if (res.confirm) {
        try {
          uni.showLoading({ title: '提交中...' })
          
          // 准备提交的数据（包含所有字段 + 状态改为待审批）
          const submitData = {
            user_id: formData.user_id,
            year_month: formData.year_month,
            base_salary: parseFloat(formData.base_salary) || 0,
            commission_amount: parseFloat(formData.commission_amount) || 0,
            bonus_amount: parseFloat(formData.bonus_amount) || 0,
            deduction_amount: parseFloat(formData.deduction_amount) || 0,
            dividend_amount: parseFloat(formData.dividend_amount) || 0,
            total_income: formData.total_income,
            remarks: formData.remarks || '',
            status: 1,  // 改回待审批状态
            rejection_reason: '',  // 清空拒绝原因
            update_time: Date.now()
          }
          
          // 调用云对象方法更新收入记录
          const incomeRecordsObj = uniCloud.importObject('dh-income_records')
          const result = await incomeRecordsObj.updateIncomeRecord(incomeId.value, submitData)
          
          uni.hideLoading()
          
          if (result.code === 200) {
            uni.showToast({ title: '已重新提交', icon: 'success' })
            setTimeout(() => {
              uni.redirectTo({ url: '/pages/business/income_records/list' })
            }, 1500)
          } else {
            uni.showToast({ title: result.message || '提交失败', icon: 'error' })
          }
        } catch (error) {
          console.error('重新提交失败:', error)
          uni.hideLoading()
          uni.showToast({ title: '提交失败', icon: 'error' })
        }
      }
    }
  })
}

function handleCancel() {
  uni.redirectTo({ url: '/pages/business/income_records/list' })
}
</script>

<style lang="scss" scoped>
.income-edit-container {
  min-height: 100vh;
  background: #f5f5f5;
  padding: 20rpx;
}

.page-header {
  background: #fff;
  padding: 40rpx;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.06);
}

.page-title {
  font-size: 44rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 12rpx;
}

.page-subtitle {
  font-size: 28rpx;
  color: #999;
  display: block;
}

.page-loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 200rpx 0;
  background: #fff;
  border-radius: 16rpx;
}

.loading-spinner {
  width: 80rpx;
  height: 80rpx;
  border: 6rpx solid #f3f3f3;
  border-top: 6rpx solid #007aff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 30rpx;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading-text {
  font-size: 28rpx;
  color: #666;
}

.form-container {
  background: #fff;
  border-radius: 16rpx;
  overflow: hidden;
}

.form-section {
  padding: 40rpx;
  border-bottom: 1rpx solid #f0f0f0;
  
  &:last-child {
    border-bottom: none;
  }
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 30rpx;
  padding-bottom: 16rpx;
  border-bottom: 2rpx solid #007aff;
}

.form-item {
  margin-bottom: 32rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.form-label {
  font-size: 28rpx;
  color: #666;
  display: block;
  margin-bottom: 16rpx;
  
  &.required::after {
    content: ' *';
    color: #ff3b30;
  }
}

.picker-view {
  padding: 20rpx;
  background: #fafafa;
  border: 1rpx solid #e0e0e0;
  border-radius: 8rpx;
}

.picker-text {
  font-size: 28rpx;
  color: #333;
}

.calculated-value {
  padding: 24rpx;
  background: #e8f5e9;
  border-radius: 8rpx;
  text-align: center;
}

.value-text {
  font-size: 48rpx;
  font-weight: bold;
  color: #2e7d32;
}

.form-textarea {
  width: 100%;
  min-height: 160rpx;
  padding: 20rpx;
  font-size: 28rpx;
  border: 1rpx solid #e0e0e0;
  border-radius: 8rpx;
  box-sizing: border-box;
  background: #fafafa;
}

.radio-group {
  display: flex;
  flex-wrap: wrap;
  gap: 24rpx;
}

.radio-item {
  display: flex;
  align-items: center;
  padding: 16rpx 24rpx;
  background: #fafafa;
  border-radius: 8rpx;
  border: 1rpx solid #e0e0e0;
}

.radio-text {
  font-size: 28rpx;
  color: #333;
  margin-left: 12rpx;
}

.error-text {
  font-size: 24rpx;
  color: #ff3b30;
  display: block;
  margin-top: 8rpx;
}

.form-actions {
  display: flex;
  gap: 20rpx;
  padding: 30rpx 40rpx;
  background: #fff;
  border-top: 1rpx solid #f0f0f0;
}

.btn {
  flex: 1;
  height: 88rpx;
  line-height: 88rpx;
  text-align: center;
  font-size: 32rpx;
  border-radius: 12rpx;
  border: none;
  
  &.btn-cancel {
    background: #f5f5f5;
    color: #666;
  }
  
  &.btn-primary {
    background: #007aff;
    color: #fff;
  }
  
  &.btn-warning {
    background: #ff9500;
    color: #fff;
  }
}

.status-display {
  display: flex;
  flex-direction: column;
  gap: 16rpx;
}

.status-badge {
  display: inline-block;
  padding: 12rpx 24rpx;
  border-radius: 8rpx;
  font-size: 28rpx;
  font-weight: 600;
  align-self: flex-start;
  
  &.status-pending {
    background-color: #dbeafe;
    color: #1e40af;
  }
  
  &.status-approved {
    background-color: #fef3c7;
    color: #92400e;
  }
  
  &.status-paid {
    background-color: #d1fae5;
    color: #065f46;
  }
  
  &.status-rejected {
    background-color: #fee2e2;
    color: #991b1b;
  }
}

.rejection-info {
  padding: 20rpx;
  background: #fff3e0;
  border-left: 4rpx solid #ff9800;
  border-radius: 8rpx;
}

.rejection-label {
  font-size: 24rpx;
  color: #e65100;
  font-weight: 600;
  display: block;
  margin-bottom: 8rpx;
}

.rejection-reason {
  font-size: 28rpx;
  color: #666;
  line-height: 1.6;
}
</style>
